import requests
import time
import random
from _md5 import md5

# params = {
#     "user_name": "neuedu",
#     "psd": "123456"
# }
# # get请求
# response = requests.get(url="http://www.baidu.com", params=params)
# print(response.status_code)
# print(response.url)

# post请求
# 需要携带表单数据
# form_data = {
#     "email": "15858282358",
#     "password": "5618676a"
# }
# url = "http://www.renren.com/PLogin.do"
# # 模拟登陆(用户名, 密码, 验证码)
# response = requests.post(url=url, data=form_data)
# print(response.status_code)
# print(response.content.decode())


# i: hello
# from: AUTO
# to: AUTO
# smartresult: dict
# client: fanyideskweb
# salt: 16003056026743
# sign: 0c127df84c63ef6aa7a9f88fd3e9746c
# lts: 1600305602674
# bv: e915c77f633538e8cf44c657fe201ebb
# doctype: json
# version: 2.1
# keyfrom: fanyi.web
# action: FY_BY_REALTlME


# js中的时间戳 1600307236675
# py中的时间戳 1600307285529.3891
user_input_str = input("请输入你要翻译的单词或句子:")
r = str(int(time.time() * 1000)) + ""
salt = r + str(random.randint(0, 9))
lts = salt[:13]
sign_str_need_md5 = "fanyideskweb" + user_input_str + salt + "]BjuETDhU)zqSxf-=B#7m"
# 创建md5加密对象
m5 = md5()
m5.update(sign_str_need_md5.encode())
# 加密两种方式 二进制(m5.digest()) & 十六进制加密(m5.hexdigest())
sign = m5.hexdigest()

url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
# 构造表单
form_data = {
    "i": user_input_str,
    "from": "AUTO",
    "to": "AUTO",
    "smartresult": "dict",
    "client": "fanyideskweb",
    "salt": salt,
    "sign": sign,
    "lts": lts,
    "bv": "e915c77f633538e8cf44c657fe201ebb",
    "doctype": "json",
    "version": "2.1",
    "keyfrom": "fanyi.web",
    "action": "FY_BY_CLICKBUTTION"
}

# 请求头
header = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36",
    "Cookie": 'OUTFOX_SEARCH_USER_ID_NCOO=1525307281.6298504; OUTFOX_SEARCH_USER_ID="-860152776@10.169.0.81"; _ga=GA1.2.929257221.1560240735; _ntes_nnid=d1a0f0601624d1ee16a28759bc1a7328,1573025887545; JSESSIONID=aaabkSGkiLd1JbemzbVnx; ___rl__test__cookies=1600307615124',
    "Referer": "http://fanyi.youdao.com/",
}
# 发送请求获取响应
response = requests.post(url=url, headers=header, data=form_data)
# 输出结果
print(response.content.decode())
